简体   繁体   English

webpack 捆绑 typescript 到 ts-loader 但获取模块未在浏览器上定义?

[英]webpack bundle typescript to ts-loader but get module is not defined on browser?

follow webpack typescript doc按照 webpack typescript 文档

when i use webpack ts-loader to convert typescript it's can't work cause module is not defined?当我使用 webpack ts-loader 转换 typescript 时它无法工作,因为模块未定义?

but when i just command tsc, this result can work on browser但是当我只是命令 tsc 时,这个结果可以在浏览器上运行

also this issues is already use gulp to fix这个问题也已经使用 gulp 来修复

but gulp use browserify to transform typescript但是 gulp 使用 browserify 来转换 typescript

so i want to use webpack to bundle my express server and client typescript!所以我想使用 webpack 来捆绑我的快递服务器和客户端打字稿!

why webpack ts-loader to transform typescript get "module is not defined" on browser?为什么 webpack ts-loader 转换 typescript 在浏览器上得到“模块未定义”?

this repositories on github github 上的这个存储库

webpack.config.js webpack.config.js

const nodeeExternals = require('webpack-node-externals');
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const serverConfig = {
  target: 'node',
  devtool: 'eval-source-map',
  node: {
    __dirname: false,
    __filename: true,
  },
  externals: [nodeExternals()],
  entry: {
    'index': './src/index.js',
    // 'public/javascripts/temibroad': './src/client/typescript/temibroad/temibroad.ts'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
    libraryTarget: 'commonjs2',
  },
  module: {   //設定你的檔案選項
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      }
    ],
  },
  // plugins: [
  //   new CopyWebpackPlugin([
  //     { from: 'src/client/views', to: 'views' },
  //     { from: 'src/client/static', to: 'public' },
  //   ])
  // ],
  optimization: {
    minimize: true,
  }
}

const clientConfig = {
  target: 'web',
  devtool: 'eval-source-map',
  node: {
    __dirname: false,
    __filename: true,
  },
  externals: [nodeExternals()],
  entry: {
    // 'index': './src/index.js',
    'public/javascripts/temibroad': './src/client/typescript/temibroad/temibroad.ts'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
    libraryTarget: 'commonjs2',
  },
  module: {   //設定你的檔案選項
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      },
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js' ],
  },
  plugins: [
    new CopyWebpackPlugin([
      { from: 'src/client/views', to: 'views' },
      { from: 'src/client/static', to: 'public' },
    ])
  ],
  optimization: {
    minimize: true,
  }
}



module.exports = [serverConfig, clientConfig];

tsconfig.json tsconfig.json

{
  "compilerOptions": {
  "target": "es5",
  "module": "commonjs",
  "sourceMap": true,
  "noEmitOnError" : false,
  "strict": true,
  "noImplicitAny": true,
  "strictNullChecks": true,
  "esModuleInterop": true,
  "forceConsistentCasingInFileNames": true
  }
}

Mh...i know why got "module is not defined" on browser, cause my output library setting.嗯......我知道为什么在浏览器上出现“模块未定义”,因为我的 output 库设置。

When my project done, then I research webpack doc, step by step check my setting, i find why i setting "commonjs2"(2??) on browser?当我的项目完成后,我研究 webpack 文档,一步一步检查我的设置,我发现为什么我在浏览器上设置“commonjs2”(2??)?

Commonjs can't work on browser immediately, so when i setting libraryTarget to "var", also setting library:'myLibrary' to call TS function, problem is solved. Commonjs 不能立即在浏览器上运行,所以当我将 libraryTarget 设置为“var”时,同时设置 library:'myLibrary' 来调用 TS function,问题就解决了。

Check out the settings below看看下面的设置

/* webpack.config.js : Webpack 的設定檔 */
// const webpack = require('webpack');
const path = require('path');

const clientConfig = {
  target: 'web',
  devtool: 'eval-source-map',
  entry: {
    // 'index': './src/index.js',
    'index': './src/index.ts'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
    library :'aaa',
    libraryTarget: 'var'
  },
  module: {   //設定你的檔案選項
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js' ],
  },
}

module.exports = [clientConfig];

index.ts索引.ts

import { gogogo } from './import';


gogogo();

export { gogogo };

console.log('你好');

import.ts导入.ts

function gogogo(str = 'gogogog'){
  console.log(str);
}

export {gogogo};

index.html索引.html

<script src="./dist/index.bundle.js"></script>
<script>
  console.log(aaa);
  aaa.gogogo('外面傳入');
</script>

Browser Console浏览器控制台

gogogog             import.ts?661f:6
好                  index.ts?71bd:7
{__esModule: true}  index.html:11 
外面傳入             import.ts?661f:6

update on 2020/06/30 with require.js使用 require.js 于 2020/06/30 更新

webpack.config.js webpack.config.js

  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].bundle.js',
    // library :'aaa',
    libraryTarget: 'amd'
  },

index.html索引.html

  <script src='https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js'></script>
  <script>
    require(['./dist/index.bundle'], function(aaa){
      console.log(aaa);
      aaa.gogogo('from aaa');
    })
  </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM